package com.baor.service.impl;

import com.baor.dao.DeliveryRecordDao;
import com.baor.dao.EquipmentDao;
import com.baor.dao.EquipmentDao2;
import com.baor.dao.Removal_recordDao;
import com.baor.domain.DeliveryRecordVO;
import com.baor.domain.Equipment;
import com.baor.domain.EquipmentVO;
import com.baor.domain.RemovalRecordVO;
import com.baor.service.ClearTheDoorService;
import com.baor.util.R;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ClearTheDoorServiceImpl implements ClearTheDoorService {

    @Autowired
    private EquipmentDao equipmentDao;

    @Autowired
    private EquipmentDao2 equipmentDao2;

    @Autowired
    private Removal_recordDao removal_recordDao;

    @Autowired
    private DeliveryRecordDao deliveryRecordDao;

    /**
     清运开门（传code码，然后把重量设置为0，状态设置为未满仓）
     */
    @Override
    public R ClearTheDoor(Map<String, Object> params) {
        // 验证设备编码参数
        if (!params.containsKey("code") || params.get("code") == null) {
            return R.er("设备编码不能为空");
        }
        try {
            String equipmentCode = params.get("code").toString().trim();
            // 根据设备编码查询设备
            Equipment equipment = equipmentDao.selectOne(
                    new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<Equipment>()
                            .eq(Equipment::getCode, equipmentCode)
            );

            if (equipment == null) {
                return R.er("未找到对应的设备信息");
            }

            // 记录清运前的重量（作为本次清运重量）
            BigDecimal removalWeight = equipment.getNowWeight() != null ? equipment.getNowWeight() : BigDecimal.ZERO;

            // 将设备当前重量设为0
            equipment.setNowWeight(BigDecimal.ZERO);
            // 重置存储状态为非满仓
            equipment.setStorageStatus(0);
            // 更新设备信息
            int rows = equipmentDao.updateById(equipment);

            if (rows <= 0) {
                return R.er("设备重量重置失败");
            }

            // 添加清运记录到removal_record表
            RemovalRecordVO removalRecord = new RemovalRecordVO();
            // 生成工单号：XQ+年月日时分秒
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
            String workOrderNo = "XQ" + LocalDateTime.now().format(formatter);
            removalRecord.setClearanceWorkOrder(workOrderNo);
            // 设置设备ID
            removalRecord.setEquipmentId(equipment.getId().longValue());
            // 设置清运重量（转换为double类型）
            removalRecord.setWeight(removalWeight.doubleValue());
            // 设置清运时间
            removalRecord.setRemovalTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            // 其他必要字段可根据实际业务补充，例如处理结果默认设为成功（1）
            removalRecord.setResult(1);

            // 插入清运记录
            int recordRows = removal_recordDao.insert(removalRecord);
            if (recordRows <= 0) {
                // 此处可根据业务需求决定是否回滚设备重量更新操作
                throw new RuntimeException("清运记录保存失败");
            }

            return R.ok("设备重量已重置为0，清运记录已保存，工单号：" + workOrderNo);

        } catch (Exception e) {
            e.printStackTrace();
            return R.er("操作异常：" + e.getMessage());
        }
    }


//    @Override
//    public R Feedback(Map<String, Object> params) {
//        if (params.containsKey("clearance_work_order") || params.get("clearance_work_order") != null) {
//
//            RemovalRecordVO removalRecord = new RemovalRecordVO();
//            removalRecord.setFeedback((Integer) params.get("feedback"));
//            int recordRows = removal_recordDao.insert(removalRecord);
//            if (recordRows <= 0) {
//                // 此处可根据业务需求决定是否回滚设备重量更新操作
//                throw new RuntimeException("上传清运结果失败");
//            }
//
//            return R.ok("清运结果，上传成功");
//        }
//        return null;
//    }

    @Override
    public R Feedback(Map<String, Object> params) {
        try {
            // 验证参数
            if (!params.containsKey("clearance_work_order") || params.get("clearance_work_order") == null) {
                return R.er("工单号不能为空");
            }

            if (!params.containsKey("feedback") || params.get("feedback") == null) {
                return R.er("反馈结果不能为空");
            }

            String workOrderNo = params.get("clearance_work_order").toString().trim();
            Integer feedback = (Integer) params.get("feedback");

            // 根据工单号查询清运记录
            RemovalRecordVO removalRecord = removal_recordDao.selectOne(
                    new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<RemovalRecordVO>()
                            .eq(RemovalRecordVO::getClearanceWorkOrder, workOrderNo)
            );

            if (removalRecord == null) {
                return R.er("未找到对应的清运记录，工单号：" + workOrderNo);
            }

            // 更新反馈结果
            removalRecord.setFeedback(feedback);

            // 如果需要，可以同时更新时间戳或其他字段
            // removalRecord.setUpdateTime(LocalDateTime.now());

            // 更新记录
            int recordRows = removal_recordDao.updateById(removalRecord);
            if (recordRows <= 0) {
                throw new RuntimeException("清运结果上传失败");
            }

            return R.ok("清运结果上传成功，工单号：" + workOrderNo);

        } catch (Exception e) {
            e.printStackTrace();
            return R.er("操作异常：" + e.getMessage());
        }
    }

    @Override
    public R DeliveryReord(Map<String, Object> params) {
        try {
            // 构建查询条件（无需分页参数）
            MPJLambdaWrapper<DeliveryRecordVO> wrapper = new MPJLambdaWrapper<>(DeliveryRecordVO.class)
                    .select(DeliveryRecordVO::getId,
                            DeliveryRecordVO::getDeliveryTime,
                            DeliveryRecordVO::getWeight)
                    .select(EquipmentVO::getAddress,EquipmentVO::getCode)
                    .leftJoin(EquipmentVO.class, EquipmentVO::getId, DeliveryRecordVO::getEquipmentId)
                    .eq(EquipmentVO::getCode, params.get("code"))
                    .orderByDesc(DeliveryRecordVO::getDeliveryTime);

            // 执行全量查询（不分页）
            List<Map<String, Object>> records = deliveryRecordDao.selectJoinMaps(wrapper);

            // 转换数据格式为前端所需
            List<Map<String, Object>> resultList = records.stream()
                    .map(this::convertToFrontendFormat)
                    .collect(Collectors.toList());

            // 封装返回结果（不含分页信息）
            Map<String, Object> result = new HashMap<>();
            result.put("list", resultList);
            result.put("totalSize", resultList.size()); // 总条数为查询结果数

            return R.ok(result);
        } catch (Exception e) {
            e.printStackTrace();
            return R.er("查询失败：" + e.getMessage());
        }
    }
    /**
     * 转换数据库字段为前端展示格式
     */
    private Map<String, Object> convertToFrontendFormat(Map<String, Object> record) {
        Map<String, Object> item = new HashMap<>();
        item.put("recordId", record.get("id"));           // 记录ID
        item.put("deliveryTime", record.get("delivery_time")); // 投递时间
        item.put("weight", record.get("weight"));         // 投递重量
        item.put("deviceAddress", record.get("address")); // 设备地址
        System.out.println(item);
        return item;
    }
}
